package com.getpebble.android;

import android.accounts.Account;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import com.getpebble.android.common.auth.PblSessionManager;
import com.getpebble.android.common.core.trace.Analytics.MobileAppBehavior;
import com.getpebble.android.common.core.trace.AnalyticsLogger;
import com.getpebble.android.common.core.trace.AndroidLogger;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.ProcessUtil;
import com.getpebble.android.common.core.util.ProcessUtil.PebbleProcess;
import com.getpebble.android.common.framework.MultiProcPreferences;
import com.getpebble.android.common.framework.PblBaseApplication;
import com.getpebble.android.common.model.PblDevice;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.config.BootConfig;
import com.getpebble.android.config.SyncBootConfig;
import com.getpebble.android.core.analytics.AnalyticsSetup;
import com.getpebble.android.core.sync.PblSyncManager;
import com.getpebble.android.framework.PblFrameworkInterface;
import com.getpebble.android.framework.developer.PblDeviceObserver;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService;
import com.getpebble.android.main.sections.support.SupportEmail;
import com.getpebble.android.notifications.util.CoreNotifications;
import com.getpebble.android.notifications.util.NotificationUtil;
import com.getpebble.android.util.HockeyAppUtil;
import com.getpebble.android.util.MigrationUtil;
import com.getpebble.android.util.UpgradeUtil;
import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;

public class PebbleApplication extends PblBaseApplication {
    public static String TAG = PebbleApplication.class.getSimpleName();
    private static CrashManagerListener hockeyAppListener = new CrashManagerListener() {
        public boolean shouldAutoUploadCrashes() {
            return true;
        }

        public String getUserID() {
            Account account = PebbleApplication.sSessionManager.getUserAccount();
            String uid = null;
            if (account != null) {
                uid = PebbleApplication.sSessionManager.getUid(account);
            }
            return uid != null ? uid : "unknown";
        }

        public String getDescription() {
            return HockeyAppUtil.getLogcatLogs();
        }

        public boolean includeDeviceData() {
            return true;
        }
    };
    private static int msActivityCount;
    private static PebbleApplication sApplicationContext = null;
    private static BootConfig sBootConfig = null;
    protected static PblDeviceObserver sDeviceObserver = null;
    private static PblFrameworkInterface sPblFrameworkInterface = null;
    private static PebbleProcess sProcess = null;
    private static PblSessionManager sSessionManager = null;
    private static PblSyncManager sSyncManager = null;

    @SuppressLint({"NewApi"})
    public void onCreate() {
        super.onCreate();
        Trace.warning(TAG, "onCreate()");
        sProcess = getCurrentProcess();
        AndroidLogger.init(this, sProcess);
        Trace.warning(TAG, "process: " + sProcess);
        Trace.warning(TAG, "DEBUG = false");
        Trace.warning(TAG, "gillette");
        Trace.warning(TAG, "PebbleAndroidInfo: " + SupportEmail.generatePebbleAndroidInfo(this));
        MigrationUtil migrationUtil = null;
        if (PebbleProcess.UI.equals(sProcess)) {
            migrationUtil = new MigrationUtil(this);
            if (migrationUtil.holoMigrationRequired()) {
                migrationUtil.doHoloMigration();
            }
        }
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        initHockeyApp();
        sApplicationContext = this;
        MultiProcPreferences.init(sApplicationContext);
        sBootConfig = BootConfig.createInstance(this);
        sSessionManager = PblSessionManager.createInstance(this);
        sSyncManager = PblSyncManager.createInstance(this);
        if (PebbleProcess.UI.equals(sProcess)) {
            UpgradeUtil.processUpgrades(this);
        }
        if (PebbleProcess.FRAMEWORK.equals(sProcess)) {
            sSyncManager.syncAll();
            GmailCheckerService.initGmailTokens();
            NotificationUtil.loadAndroidApps();
        }
        bindToFrameworkService();
        AnalyticsSetup.initializeMobileAnalytics(this);
        createDeviceObserver();
        if (PebbleProcess.UI.equals(sProcess)) {
            syncBootConfig();
            if (migrationUtil != null) {
                PblDevice lastConnectedDevice = migrationUtil.getLastConnectedDevice();
                if (lastConnectedDevice != null) {
                    Trace.debug(TAG, "Migration: requesting connect to " + lastConnectedDevice);
                    getFrameworkInterface().connectToDevice(lastConnectedDevice);
                }
            }
        }
        disableNotificationsForCoreApps();
    }

    protected void initHockeyApp() {
        CrashManager.register(this, "fcca466be5aa6ae73c82d7729866d502", hockeyAppListener);
    }

    protected void createDeviceObserver() {
        sDeviceObserver = new PblDeviceObserver(this);
        sDeviceObserver.register(this);
    }

    protected void syncBootConfig() {
        SyncBootConfig.syncBootConfigIfRequired(null, getApplicationContext(), null, true);
    }

    protected void disableNotificationsForCoreApps() {
        CoreNotifications.disableNotificationsForNativeApps(this);
    }

    protected PebbleProcess getCurrentProcess() {
        return ProcessUtil.getProcess(this);
    }

    public static PblDevice getConnectedDevice() {
        return sDeviceObserver.getDevice();
    }

    public static boolean isConnected() {
        return getConnectedDevice() != null;
    }

    public static PblDeviceRecord getLastConnectedDeviceRecord() {
        if (sDeviceObserver == null) {
            return null;
        }
        return sDeviceObserver.getLastConnectedDeviceRecord();
    }

    public static PblDeviceRecord getConnectedDeviceRecord() {
        if (sDeviceObserver == null) {
            return null;
        }
        return sDeviceObserver.getPblDeviceRecord();
    }

    public static void addConnectedDeviceChangeListener(ConnectedDeviceChangeListener listener) {
        sDeviceObserver.addListener(listener);
    }

    public static void removeConnectedDeviceChangeListener(ConnectedDeviceChangeListener listener) {
        sDeviceObserver.removeListener(listener);
    }

    public static void bindToFrameworkService() {
        if (sApplicationContext == null) {
            Trace.error(TAG, "context is null");
        } else {
            sApplicationContext.bindToFrameworkServiceInternal();
        }
    }

    protected void bindToFrameworkServiceInternal() {
        if (sPblFrameworkInterface == null) {
            Trace.debug(TAG, "Binding to framework service");
            sPblFrameworkInterface = new PblFrameworkInterface(this, sProcess);
            sPblFrameworkInterface.bindService();
        }
    }

    public void onTerminate() {
        AnalyticsSetup.terminateMobileAnalytics();
        sSessionManager = null;
        sSyncManager = null;
        sBootConfig = null;
        if (sDeviceObserver != null) {
            sDeviceObserver.unregister(this);
            sDeviceObserver = null;
        }
        if (sPblFrameworkInterface != null) {
            sPblFrameworkInterface.unBindService();
            sPblFrameworkInterface = null;
        }
        sApplicationContext = null;
        super.onTerminate();
    }

    public static PblSessionManager getSessionManager() {
        return sSessionManager;
    }

    public static PblSyncManager getSyncManager() {
        return sSyncManager;
    }

    public static BootConfig getBootConfig() {
        return sBootConfig;
    }

    public static PblFrameworkInterface getFrameworkInterface() {
        return sPblFrameworkInterface;
    }

    public SharedPreferences getSharedPreferences(String name, int mode) {
        return new MultiProcPreferences(getApplicationContext(), name);
    }

    public SharedPreferences getNativeSharedPreferences(String name, int mode) {
        return super.getSharedPreferences(name, mode);
    }

    public static void onActivityOnStart() {
        msActivityCount++;
        if (msActivityCount == 1) {
            onApplicationForeground();
        }
    }

    private static void onApplicationForeground() {
        MobileAppBehavior.logMobileAppForegrounded();
        AnalyticsLogger.uploadAnalytics();
    }

    public static void onActivityOnStop() {
        msActivityCount--;
        if (msActivityCount == 0) {
            onApplicationBackground();
        }
    }

    private static void onApplicationBackground() {
        MobileAppBehavior.logMobileAppBackgrounded();
        AnalyticsLogger.uploadAnalytics();
    }

    public static Context getAppContext() {
        return sApplicationContext;
    }
}
